<?php
/**
* @package controller
* @file indexController.php
* @date 19.08.2009
* @version 1.0
* @copyright sample
* @author 
* @todo phpDoc comments
*/
require_once 'Zend/Controller/Action.php';

class Register_IndexController extends Cms_Controller_Action
{
	
	public function init()
	{
		//Zend_Layout::getMvcInstance()->setLayoutPath('../app_mvc/index/admin/layouts');
		$this->view->siteTitle = 'sample - Registration';
		
		
	}
	public function indexAction()    
	{ 
		global $turnover,$companysize,$major;
		$this->view->first_name = '';
		$this->view->last_name = '';
		$this->view->age = '';
		$this->view->email_address = '';
		$this->view->company_name = '';
		$this->view->password = '';
		$this->view->captachaMessage = '';
		$this->view->institution = '';
		//echo '<pre>';print_r($institutions);exit;
		$this->view->turnover = $turnover;
		$this->view->currentYear = $companysize;
		$this->view->major = $major;
		$this->view->uty = '';
		$this->view->uty = '';
		$companyownership = Doctrine::getTable('OrgTypes')->getTypes(1);
		
		foreach($companyownership as $oships)
		{
			$ships[$oships['id']] =  $oships['description'];
			$this->view->oships = $ships;
		}
		$companyownership = Doctrine::getTable('OrgTypes')->getTypes(1);
		
		foreach($companyownership as $oships)
		{
			$ships[$oships['id']] =  $oships['description'];
			$this->view->ships = $ships;
		}
		$sectors = Doctrine::getTable('OrgTypes')->getTypes(2);
		
		foreach($sectors as $sector)
		{
			$sectorlist[$sector['id']] =  $sector['description'];
			$this->view->sectorlist = $sectorlist;
		}
		$csrs = Doctrine::getTable('OrgTypes')->getTypes(3);
		
		foreach($csrs as $csr)
		{
			$csrdrivers[$csr['id']] =  $csr['description'];
			$this->view->csrdrivers = $csrdrivers;
		}
		$countries = Doctrine::getTable('Countries')->getCountries();
		
		foreach($countries as $allcountries)
		{
			$selectedCountries[$allcountries['id']] =  $allcountries['name'];
			$this->view->allcountries = $selectedCountries;
		}
		
		$countries = Doctrine::getTable('Countries')->getCountries();
		
		foreach($countries as $allcountries)
		{
			$selectedCountries[$allcountries['id']] =  $allcountries['name'];
			$this->view->allcountries = $selectedCountries;
		}
		
		$states = Doctrine::getTable('States')->getStates();
		
		foreach($states as $allstates)
		{
			$selectedStates[$allstates['stateName']] =  $allstates['stateName'];
			$this->view->allstates = $selectedStates;
		}
		
		//$this->view->allcountries = $countries;
		//echo '<pre>';print_r($selectedCountries);exit;

	}
	public function uniqemailAction()
	{
		$this->_helper->layout->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
		$decisionDetails = Doctrine::getTable('Organizations')->findUinqueEmail($_POST['email']);
		if($decisionDetails[0]->numCount){
			echo 'Email address already exists.';
		} else {
			echo '';
		}
	}
	public function chkcaptchaAction()
	{
		$this->_helper->layout->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
		if(empty($_SESSION['captcha']) || (trim(strtolower($_POST['captcha'])) != $_SESSION['captcha'])){
			echo 'Your input did not match up.';
		} else {
			echo 1;
		}
	}
	
	
	public function saveAction()
	{
	/*	echo $_SESSION['captcha'];*/
		//echo '<pre>';print_r($_POST);exit;
		$userSaved = 0;

		$emailId = addslashes(trim($_POST['emailAddress']));

			if($emailId!='') {
				$checkRecord = Doctrine::getTable('Organizations')->checkUniqueRecord($emailId);
				if($checkRecord->numCount==0){
					$userSaved = Doctrine::getTable('Organizations')->addUser($_POST);
					//echo $userSaved;exit;
				} 
				if( $userSaved > 0 ){
/*					//include('../lib/mail/SendEmail.php');
					global $regSubject;
					global $regMessage;
					//global $serverAddress;
					$Body = str_replace("<FULLNAME>", $_POST['firstName'], $regMessage);
					$activationLink = $this->CONFIG->serverAddress.'register/index/activate/'.base64_encode(
					$userSaved).'/'.base64_encode($emailId);
					$mailBody = str_replace("<ACTIVATIONLINK>", $activationLink, $Body);
					//sendMail($emailId,$regSubject,$mailBody);
					$this->view->message = 'Registration process successfully completed.';
					$this->view->success = 1;*/
				} else {
					 'Your registration has already been submitted. Please check your email for the activation link.';
					exit;
				}
				$this->_redirect('/register/index/save2/'.base64_encode($userSaved));
		}
	}
	public function save2Action()
	{
		$id = $this->_getParam('id')? base64_decode($this->_getParam('id')):0;
		//$id = base64_decode($this->_getParam('id'));
		 $id;
		$settings = 0;
		$totalPillers = Doctrine::getTable('UserRelationPillers')->getUserTyupe($id);
		//echo '<pre>';print_r($totalPillers);exit;
		if(count($totalPillers)>0)
		{
			$settings = 1;			
		}
		$cats = array();
		$results = Doctrine::getTable('PillarCategory')->getPillarCategories(8);
		if(count($results)>0)
		{
			foreach($results as $categories)
			{
				$cats[$categories['id']] =  $categories['category_name'];
			}
		}
		$this->view->categories = $cats;
		$this->view->userId = $id;
		$this->view->settings = $settings;
		$this->view->uty = '';
		//echo '<pre>';print_r($cats);exit;
	}
	public function saveTypeAction()
	{
	
		include('../lib/mail/SendEmail.php');
		//echo '<pre>';print_r($_POST);exit;
		$id = isset($_POST['userId'])? $_POST['userId']:0; //exit;
		//echo $id = base64_decode($this->_getParam('id'));
		//exit;
		$results = Doctrine::getTable('Organizations')->getUserDetailsById($id);
		//echo '<pre>';print_r($results);exit;
		$value = array();
		$value[0] = 1;
		$value[1] = 2;
		$value[2] = 3;
		$value[3] = 4;
		$ispecific = $_POST['cats'];
		if($_POST['otype'] == 2)
		{
			$price = 4000;
			$value[4] = isset($_POST['corporate'])? $_POST['corporate']:0;
			if($value[4]!=0)
			{
				$price = $price + 500;
			}
			$value[5] = isset($_POST['local'])? $_POST['local']:0;
			if($value[5]!=0)
			{
				$price = $price + 500;
			}
			$value[6] = isset($_POST['philanthropy'])? $_POST['philanthropy']:0;
			if($value[6]!=0)
			{
				$price = $price + 500;
			}
			
		}
		else if($_POST['otype'] == 3)
		{
			$value[4] = 5;
			$value[5] = 6;
			$value[6] = 7;
			$price = 7500;
			
		} else {
			$value[4] = 0;
			$value[5] = 0;
			$value[6] = 0;
			$price = 2000;
		}
		if($_POST['cats'] !=0)
		{
			$value[7] = $_POST['cats'];
		}
		foreach($value as $key=>$ivalues)
		{
			if($key == 7)
			{
				$pillerType = 2;
			} else {
				$pillerType = 1;
			}
			if($ivalues == 0)
			{
			
			} else {
				Doctrine::getTable('UserRelationPillers')->addRelations($ivalues,$id,$pillerType,$_POST['otype']);
				$this->view->message = 'Registration process successfully completed.';
				$this->view->success = 1;
			}
		}

		global $regSubject;
		global $regMessage;
		//global $serverAddress;
		$Body = str_replace("<FULLNAME>", $results['name_organisation'], $regMessage);
		$activationLink = $this->CONFIG->serverAddress.'user/login/index/'.base64_encode($_POST['userId']);
		$mailBody = str_replace("<ACTIVATIONLINK>", $activationLink, $Body);
		sendMail($results['email_id'],$regSubject,$mailBody);
		$this->_redirect('/paypal/index/index/'.base64_encode($id).'/'.base64_encode($price));
		
		//exit;
		//echo '<pre>';print_r($value);exit;
		//$results = Doctrine::getTable('PillarCategory')->addRelations($value5,$value6,$value7,$id,$ispecific);
		
	}
	public function saveConfirmAction()
	{
	
	}
	public function activateAction()
	{
		//var_dump($this->getRequest());
		$Id = $this->_getParam('id');
		$email = $this->_getParam('current_page');
		$userId = base64_decode($Id);
		$emailId = base64_decode($email);
		$activate = Doctrine::getTable('User')->activateUser($userId,$emailId);
		//echo ($activate);exit;
		if($activate>0){
			$this->view->activation = 'Activation successfully completed, please login and use our services.';
		} else {
			$this->view->activation = 'This registration is already active. Please use your credentials to login';
		}
	}
	public function forgotPasswordAction()
	{
			$this->view->fpwreq ='';
			$id = $this->_getParam('id');
			if($id == 'fail')
			$this->view->fpwreq = 'Email address does not exist in database.';
			$this->view->siteTitle = 'sample - Forgot Password';
	
	}
	public function resetPasswordAction()
	{
		$emailId = addslashes($_POST['emailAddress']);
		//Store token with userdata in database
		$token = getUniqueCode('10');
		$token = base64_encode($token);
		$tokentime = date("Y-m-d H:i:s", time()) ;
		$userDetails = Doctrine::getTable('Organizations')->getUserId($emailId);
		//echo '<PRE>';print_r($userDetails);exit;
		$resultCount = count($userDetails);
		if( $resultCount>0 && $userDetails['email_id']!=''){
			$deletePassword = Doctrine::getTable('ChangePassword')->deleteToken($emailId);
			//echo $deletePassword;exit;
			$insForgotPassword = Doctrine::getTable('ChangePassword')->setToken($userDetails['org_id'],
			$emailId,$token,$tokentime);
			//global $serverAddress;
			global $forgotPasswordSubject;
			global $frogotPasswordMessage;
			include('../lib/mail/SendEmail.php');
			$Body = str_replace("<FULLNAME>",$userDetails['name_organisation'], $frogotPasswordMessage);
			$passwordLink = $this->CONFIG->serverAddress.'register/index/change-password/'.base64_encode($userDetails['org_id']).'/'.$token;
			$mailBody = str_replace("<PASSWORDLINK>", $passwordLink, $Body);
			sendMail($emailId,$forgotPasswordSubject,$mailBody);
		}
		else
			{
				$this->_redirect('/register/index/forgot-password/fail');

			}
				
	}
	public function changePasswordAction()
	{
		$id = $this->_getParam('id');
		$userId = base64_decode($id);
		$token = $this->_getParam('current_page');
		$checktoken = Doctrine::getTable('ChangePassword')->getToken($token);
		$this->view->id = $userId;
		//echo count($checktoken);exit;
		if(count($checktoken) > 0) {
		
			if( $checktoken[0]->id != '' && $checktoken[0]->id != 0 ){
				if($checktoken[0]->token == $token ){
					$this->view->token_id = 1;
					$this->view->token = $token;
					//$this->view->token = $checktoken[0]->token;
					$this->view->email = $checktoken[0]->email;
				}
				else
					$this->view->token_id = 2;
			}
		}
		else
			$this->view->token_id = 2;
	}
	public function savePasswordAction()
	{
		//echo '<pre>';print_r($_POST);exit;
		$message = '';
		$newPassword = md5($_POST['password1']);
		$email = $_POST['email'];
		$userId = $_POST['id'];
		if($_POST['email']!='' && $_POST['password1']!='') {
			$changePassword = Doctrine::getTable('Organizations')->changePassword($userId,$newPassword);
			$changeStatus = Doctrine::getTable('ChangePassword')->deleteToken($email);
			$message = 'Password changed successfully.';
		}
		$this->view->message = $message;
	}
	
	public function manageAction()
	{
		$currentPage = isset($_POST['page'])? $_POST['page']:1;
		$resultsPerPage = isset($_POST['rp'])? $_POST['rp']:10;
		$quickSearchType = isset($_POST['qtype'])? $_POST['qtype']:'';
		$query = isset($_POST['query'])? $_POST['query']:'';
		$sortName = $_POST['sortname'];
		$sortOrder = $_POST['sortorder'];	  	
		$letterPressed=isset($_POST['letter_pressed'])? $_POST['letter_pressed'] :'';
		////////for get the details of manage sector grid///////////////////
		$pager=Doctrine::getTable('User')->getContentGrid($currentPage,$resultsPerPage,$quickSearchType,$query,$sortName,$sortOrder,$letterPressed);
		$res = $pager->execute(array(1), Doctrine::HYDRATE_ARRAY);
		$total = $pager->getNumResults();
		
		$rows = NULL;
		
		foreach($res as $result) {
			$row =& $rows[];
			$row['id'] = $result['user_id'];
			$row['cell'][] = $result['user_id'];
			$row['cell'][] = $result['first_name'];
			$row['cell'][] = $result['email_address'];
			$row['cell'][] = $result['user_type'];
			$row['cell'][] = $result['active'];
		}
		$jsonData['page'] = $currentPage;
		$jsonData['total'] = $total;
		$jsonData['rows']  = $rows;
		$this->_helper->json->sendJson($jsonData);
	}

	public function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2) {
		$vowels .= "AEUY";
	}
	if ($strength & 4) {
		$consonants .= '23456789';
	}
	if ($strength & 8) {
		$consonants .= '@#$%';
	}
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

public function paypalAction()
{

require_once('../lib/paypal.class.php');  // include the class file
$p = new paypal_class;             // initiate an instance of the class
$p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';   // testing paypal url
//$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
            
// setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php')
//$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

echo $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];exit;

$this_script = 'http://sample.local';

//echo '<pre>';print_r($_GET);exit;
// if there is not action variable, set the default action of 'process'
if (empty($_GET['action'])) $_GET['action'] = 'process';  

switch ($_GET['action']) {
    
   case 'process':      // Process and order...

      // There should be no output at this point.  To process the POST data,
      // the submit_paypal_post() function will output all the HTML tags which
      // contains a FORM which is submited instantaneously using the BODY onload
      // attribute.  In other words, don't echo or printf anything when you're
      // going to be calling the submit_paypal_post() function.
 
      // This is where you would have your form validation  and all that jazz.
      // You would take your POST vars and load them into the class like below,
      // only using the POST values instead of constant string expressions.
 
      // For example, after ensureing all the POST variables from your custom
      // order form are valid, you might have:
      //
      // $p->add_field('first_name', $_POST['first_name']);
      // $p->add_field('last_name', $_POST['last_name']);
      
      $p->add_field('business', 'sravan_1321173886_biz@gmail.com');
      $p->add_field('return', $this_script.'?action=success');
      $p->add_field('cancel_return', $this_script.'?action=cancel');
      $p->add_field('notify_url', $this_script.'?action=ipn');
      $p->add_field('item_name', 'Paypal Test Transaction');
      $p->add_field('amount', '1.99');

      $p->submit_paypal_post(); // submit the fields to paypal
      //$p->dump_fields();      // for debugging, output a table of all the fields
      break;
      
   case 'success':      // Order was successful...
   
      // This is where you would probably want to thank the user for their order
      // or what have you.  The order information at this point is in POST 
      // variables.  However, you don't want to "process" the order until you
      // get validation from the IPN.  That's where you would have the code to
      // email an admin, update the database with payment status, activate a
      // membership, etc.  
 
      echo "<html><head><title>Success</title></head><body><h3>Thank you for your order.</h3>";
      foreach ($_POST as $key => $value) { echo "$key: $value<br>"; }
      echo "</body></html>";
      
      // You could also simply re-direct them to another page, or your own 
      // order status page which presents the user with the status of their
      // order based on a database (which can be modified with the IPN code 
      // below).
      
      break;
      
   case 'cancel':       // Order was canceled...

      // The order was canceled before being completed.
 
      echo "<html><head><title>Canceled</title></head><body><h3>The order was canceled.</h3>";
      echo "</body></html>";
      
      break;
      
   case 'ipn':          // Paypal is calling page for IPN validation...
   
      // It's important to remember that paypal calling this script.  There
      // is no output here.  This is where you validate the IPN data and if it's
      // valid, update your database to signify that the user has payed.  If
      // you try and use an echo or printf function here it's not going to do you
      // a bit of good.  This is on the "backend".  That is why, by default, the
      // class logs all IPN data to a text file.
      
      if ($p->validate_ipn()) {
          
         // Payment has been recieved and IPN is verified.  This is where you
         // update your database to activate or process the order, or setup
         // the database with the user's order details, email an administrator,
         // etc.  You can access a slew of information via the ipn_data() array.
  
         // Check the paypal documentation for specifics on what information
         // is available in the IPN POST variables.  Basically, all the POST vars
         // which paypal sends, which we send back for validation, are now stored
         // in the ipn_data() array.
  
         // For this example, we'll just email ourselves ALL the data.
         $subject = 'Instant Payment Notification - Recieved Payment';
         $to = 'YOUR EMAIL ADDRESS HERE';    //  your email
         $body =  "An instant payment notification was successfully recieved\n";
         $body .= "from ".$p->ipn_data['payer_email']." on ".date('m/d/Y');
         $body .= " at ".date('g:i A')."\n\nDetails:\n";
         
         foreach ($p->ipn_data as $key => $value) { $body .= "\n$key: $value"; }
         mail($to, $subject, $body);
      }
      break;
 }  

}
	public function termsAction()
	{
		$this->_helper->layout->disableLayout();
		$results = Doctrine::getTable('SiteContent')->getDetails(8);
		//echo '<pre>';print_r($results);exit;
		$this->view->details = $results[0];
	}

}

?>
